from Controller.BaseController import BaseController
from Common.DuplicatedInstanceError import DuplicatedInstanceError
from Common.GroupOrg import Group 
from Utility import FormData
from Utility import UserRole
from Utility import ViewName
from Utility import TemplateValueName

class CreateGroupController(BaseController):
    """
    This page should be accessable to company admin
    """
 
    def get(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.CompanyAdmin, "/create/group"):
            return

        # dispaly the company name for current user in UI
        template_values = {'CompanyName': u.Ref_Company.CompanyName}
            
        self.Render(ViewName.D_CREATEGROUP, template_values)
    
    
    def post(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.CompanyAdmin, "/create/group"):
            return
        
        groupName = self.request.get(FormData.GROUP_NAME)
        company = u.Ref_Company
        
        template_values = {'CompanyName': u.Ref_Company.CompanyName}
        
        try:
            g = Group(parent=company,
                      key_name=groupName,
                      GroupName=groupName,
                      Ref_Company=company)
            g.TransactionPut()
            template_values[TemplateValueName.SUCCESS_MESSAGE] = "Mew Group, " + groupName + ", was created successfully!"
        except DuplicatedInstanceError:
            template_values[TemplateValueName.ERROR_MESSAGE] = "Group, " + groupName + ", already exists!"
            #self.response.out.write(Group.get_by_key_name(groupName, company).key())
            
        self.Render(ViewName.D_CREATEGROUP, template_values)
        
        #self.response.out.write("<br />")
        #self.response.out.write(db.Key.from_path("Group", groupName, parent=company.key()))


"""
<select id="ddl_companykey" name="ddl_companykey">
{% for x in Companys %}
    <option value="{{ x.key }}">{{ x.CompanyName }}</option>
{% endfor %}
</select>
"""
